package com.mcc.websocket.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import com.mcc.common.core.domain.entity.SysUser;
import com.mcc.common.core.domain.model.LoginUser;
import com.mcc.framework.web.service.TokenService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashSet;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * websocket 消息处理
 *
 * @author gxy
 */
@Component
@ServerEndpoint("/websocket/mcc")
@Slf4j
@Data
public class WebSocketController {

    public static CopyOnWriteArraySet<WebSocketController> sessions = new CopyOnWriteArraySet<>();

    private static TokenService tokenService;

    @Autowired
    public void setTokenService(TokenService tokenService) {
        WebSocketController.tokenService = tokenService;
    }

    private Session session;

    private SysUser user;

    /**
     * 页面注册监听事件
     * gatewayUpdate
     * devUpdate
     * slaveUpdate
     */

    private HashSet<String> events = new HashSet<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        try {
            this.session = session;
            sessions.add(this);
//            System.out.println("onOpen");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session) {
        try {
            sessions.remove(this);
//            System.out.println("onClose");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) {
        try {
            exception.printStackTrace();
            if (session.isOpen()) {
                // 关闭连接
                session.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(Session session, String message) {
        try {
//            System.out.println(message);
            JSONObject json = new JSONObject(message);
            if (json.containsKey("token") && this.user == null) {
                String token = json.getStr("token");
                LoginUser loginUser = tokenService.getLoginUser(token);
                if (loginUser != null) {
                    this.user = loginUser.getUser();
                }
            }
            if (json.containsKey("event")) {
                String event = json.getStr("event");
                boolean cancel = Convert.toBool(json.get("cancel"), false);
                if (cancel) {
                    this.events.remove(event);
                } else {
                    this.events.add(event);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
